/*
 * Author: Alvin
 * Modified By: Alvin
 * Created Date: 2023-07-20 17:50:48
 * Last Modified: 2023-07-25 17:33:47
 * Description:
 */
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:native_dart_package/http/request/exception/api_exception.dart';
import 'package:native_dart_package/native_dart_package.dart';

import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/list_empty_widget.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/time_range_picker.dart';
import 'package:yt_devops/components/tips.dart';
import 'package:yt_devops/components/yt_bottom_picker.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/pages/devices/device_list/components/filter_site_tags.dart';
import 'package:yt_devops/pages/devices/device_list/components/filter_status_tags.dart';
import 'package:yt_devops/pages/tasks/task_list/task_list_model.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/navigate_utils.dart';

import 'list_page_item_view.dart';

class ListPageView extends StatefulWidget {
  ListPageView({super.key, required this.service, required this.tabIndex});
  int tabIndex;
  final Future Function(Map) service;
  @override
  State<StatefulWidget> createState() {
    return ListPageViewState();
  }
}

class ListPageViewState extends State<ListPageView>
    with AutomaticKeepAliveClientMixin {
  RefreshController refreshController =
      RefreshController(initialRefresh: false);
  int pageNum = 1;
  int pageSize = 10;
  List<TaskListModel>? state;
  // 过滤参数
  Map<String, dynamic> extraParam = {};
  String startTime = '';
  String endTime = '';

  /// 选中任务状态
  int? statusValue;
  //已选中的站点列表
  List<SiteTagModel> selectedSites = [];

  @override
  void initState() {
    super.initState();
    Log.d('ListPageView===initState');
    loadList(refereshType: RefereshType.initial);
  }

  Map<String, dynamic> setQueryParam() {
    String siteIds = selectedSites.map((e) => e.siteId).toList().join(',');
    Map<String, dynamic> extraParam = {
      'startTime': startTime,
      'endTime': endTime,
      'siteIds': siteIds,
      'status': statusValue
    };
    return extraParam;
  }

  Future<void> loadList(
      {RefereshType refereshType = RefereshType.refresh}) async {
    var params = {
      'current': pageNum,
      'pageSize': pageSize,
      ...extraParam,
      ...setQueryParam()
    };

    Configs.httpClient.requestWithLoading(() async {
      var list = await widget.service(params);

      var temp = List.of(list['list'])
          .map((item) => TaskListModel.fromJson(item))
          .toList();
      if (refereshType == RefereshType.refresh ||
          refereshType == RefereshType.initial) {
        state = temp;
      } else {
        state!.addAll(temp);
      }
      endRefresh(temp);
      if (mounted) {
        setState(() {});
      }
    }, onError: (error) {
      showError(error.message ?? '请求错误');
      endRefresh(null);
      return true;
    },
        showLoading: refereshType == RefereshType.refresh ||
                refereshType == RefereshType.load
            ? true
            : false);
  }

  void onRefresh({RefereshType refereshType = RefereshType.refresh}) {
    pageNum = 1;
    // refreshController.requestRefresh();
    loadList(refereshType: refereshType);
  }

  void endRefresh(List<TaskListModel>? list) {
    if (refreshController.isRefresh) {
      refreshController.refreshCompleted();
      if ((list?.length ?? 0) >= pageNum) {
        refreshController.resetNoData();
      }
    } else {
      if (list == null) {
        refreshController.loadFailed();
      } else if ((list.isEmpty) || ((list.length) < pageNum)) {
        refreshController.loadNoData();
      } else {
        refreshController.loadComplete();
      }
    }
  }

  void onLoad() {
    pageNum++;
    loadList(refereshType: RefereshType.load);
  }

  toDetails(int id, TaskType type) {
    NavigateUtils.toTaskDetail(id, type)?.then((value) {
      if (value == true) {
        onRefresh();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: refreshController,
      enablePullDown: true,
      enablePullUp: true,
      header: ListTips.classicHeader,
      footer: ListTips.generateClassicFooter,
      onLoading: () => onLoad(),
      onRefresh: () => onRefresh(),
      child: listBody(),
    );
  }

  Widget listBody() {
    if (state == null) {
      return const SizedBox.shrink();
    } else if (state!.isEmpty) {
      return ListEmptyWidget(topPosition: 82);
    } else {
      return ListView.builder(
        padding: EdgeInsets.symmetric(vertical: 10.h),
        physics: const AlwaysScrollableScrollPhysics(),
        // padding: EdgeInsets.fromLTRB(15.w, 95.h, 15.w, 10.h),
        itemBuilder: (context, index) {
          if ((state!.isEmpty)) {
            return ListEmptyWidget(topPosition: 82);
          } else {
            var data = state![index];
            return ListPageItemView(
              model: data,
              onItemTaped: (model) => toDetails(model.id!, model.type!),
            );
          }
        },
        itemCount: state!.length,
      );
    }
  }

  toFilter(BuildContext context) {
    ytBottomPicker(context, mainButtonOnTap: () {
      onRefresh(refereshType: RefereshType.initial);
      Get.back();
    }, resetTap: (setstate) {
      reset(setstate);
    }, builder: (context) {
      return StatefulBuilder(
        builder: (context, setState) => Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TimeRangePicker(
              title: ResKey.creationTime.tr,
              padding: EdgeInsets.only(right: 16.w),
              startTime: startTime,
              endTime: endTime,
              onChange: (start, end) {
                startTime = start;
                endTime = end;
              },
            ),
            SizedBox(
              height: 3.h,
            ),
            FilterSiteTags(
              selectedSites: selectedSites,
              onChange: (sites) {
                selectedSites = sites;
              },
            ),
            getStatusTags() ?? const Text('')
          ],
        ),
      );
    });
  }

  FilterStatusTags? getStatusTags() {
    var curIndex = widget.tabIndex;
    Log.d('curIndex=' + curIndex.toString());
    // Log.d('controller.statusValue=' + controller.statusVrepairStatusValuealue.toString());
    switch (curIndex) {
      case 0:
        return FilterStatusTags<InstallTaskStatusType>(
          InstallTaskStatusType.values,
          labelName: (status) => status.label,
          tagWidth: 75.w,
          title: ResKey.workOrderStatus.tr,
          selectTags: statusValue == null
              ? []
              : [
                  $enumDecodeNullable(
                      $InstallTaskStatusTypeEnumMap, statusValue)!
                ],
          onSelect: (stuatus) {
            if (stuatus != null && stuatus.isNotEmpty) {
              statusValue = stuatus[0].value;
            }
          },
        );
      case 1:
        return FilterStatusTags<RepairTaskStatusType>(
          RepairTaskStatusType.values,
          labelName: (status) => status.label,
          tagWidth: 75.w,
          title: ResKey.workOrderStatus.tr,
          selectTags: statusValue == null
              ? []
              : [
                  $enumDecodeNullable(
                      $RepairTaskStatusTypeEnumMap, statusValue)!
                ],
          onSelect: (stuatus) {
            if (stuatus != null && stuatus.isNotEmpty) {
              statusValue = stuatus[0].value;
            }
          },
        );
      case 2:
        return FilterStatusTags<ReportTaskStatusType>(
          ReportTaskStatusType.values,
          labelName: (status) => status.label,
          tagWidth: 75.w,
          title: ResKey.workOrderStatus.tr,
          selectTags: statusValue == null
              ? []
              : [
                  $enumDecodeNullable(
                      $ReportTaskStatusTypeEnumMap, statusValue)!
                ],
          onSelect: (stuatus) {
            if (stuatus != null && stuatus.isNotEmpty) {
              statusValue = stuatus[0].value;
            }
          },
        );
      default:
        return null;
    }
  }

  reset(void Function(void Function()) setstate) {
    startTime = '';
    endTime = '';
    selectedSites.clear();
    statusValue = null;
    setstate(() {});
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
